package com.knife.member.stat;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.knife.member.BaseHibernateDAO;


/**
 * 数据库工具类 1，查找DataSource获取数据库连接 2，释放连接资源
 */
public class DBHandle {
	/**
	 * 获取数据库连接 1，初始化上下文环境Context
	 * 2，在Context中查找DataSource，名字预先给定，这里为：“java:comp/env/jdbc/stat”
	 * 3，如果DataSource不为空，就从DataSource中取出一个连接
	 */
	public synchronized static Connection getConn() throws Exception {
		/*
		 * Connection conn = null; DataSource ds = null; Context ctx = new
		 * InitialContext(); ds = (DataSource)
		 * ctx.lookup("java:comp/env/jdbc/stat"); if (ds != null) { conn =
		 * ds.getConnection(); }
		 */
		BaseHibernateDAO dao = new BaseHibernateDAO();
		org.hibernate.Session s = dao.getSession();
		@SuppressWarnings("deprecation")
		Connection conn = s.connection();
		return conn;
	}

	/**
	 * 释放连接相关资源，请注意相关次序 1，先释放结果集 2，再释放语句句柄 3，最后释放连接
	 */
	public static void closeResource(Statement st, ResultSet rs, Connection cnn) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (Exception es) {
		}
		try {
			if (st != null) {
				st.close();
			}
		} catch (Exception es) {
		}
		try {
			if (cnn != null) {
				cnn.close();
				cnn = null;
			}
		} catch (Exception es) {
		}
	}

	/**
	 * 使用DriverManager获取数据库连接
	 */
	@SuppressWarnings("deprecation")
	public static Connection getConnection() throws Exception {
		/*
		 * String driver = "org.gjt.mm.mysql.Driver"; String urlString =
		 * "jdbc:mysql://localhost/stat"; String user = "root"; String pwd =
		 * "38574638"; Class.forName(driver); Connection cnn =
		 * DriverManager.getConnection(urlString, user, pwd);
		 */
		BaseHibernateDAO dao = new BaseHibernateDAO();
		org.hibernate.Session s = dao.getSession();
		Connection cnn = s.connection();
		return cnn;
	}

}
